<template>
    <div>
        <el-button type="text" @click="saveUI">添加用户</el-button>
        <el-dialog title="" :visible.sync="dialogFormVisible">
            <el-form :model="form">
                <el-form-item label="用户姓名" :label-width="formLabelWidth">
                    <el-input v-model="form.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" :label-width="formLabelWidth">
                    <el-input v-model="form.password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="年龄" :label-width="formLabelWidth">
                    <el-input v-model="form.userAge" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="电话" :label-width="formLabelWidth">
                    <el-input v-model="form.userPhone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="照片" :label-width="formLabelWidth">
                    <input type="file" ref="file" /><br>
                    <span v-if="this.form.userId">
                        <img :src="`http://localhost:7758/images/${form.photo}`" width="100px" />
                    </span>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitform">确 定</el-button>
            </div>
        </el-dialog>

        <!--分配角色模态框-->
        <el-dialog title="角色分配" :visible.sync="dialogRoleFormVisible" width="800px">
            <template>
                <div>
                    为{{user.username}}分配角色<br>
                    <el-transfer v-model="value" :data="roles" :titles="['备选角色', '已有角色']"
                        :props="{ key: 'roleId', label: 'roleName' }"></el-transfer>
                         <el-button @click="doDistributeRole(user.userId)">分配</el-button> 
                </div>
            </template>
        </el-dialog>
        <!--分配角色模态框结束-->

        <el-table :data="tableData" stripe style="width: 100%">
            <el-table-column prop="userId" label="编号" width="100">
            </el-table-column>
            <el-table-column prop="username" label="姓名" width="180">
            </el-table-column>
            <el-table-column prop="userAge" label="年龄" width="100">
            </el-table-column>
            <el-table-column prop="userPhone" label="电话" width="180">
            </el-table-column>
            <el-table-column prop="photo" label="照片" width="180">
                <template slot-scope="scope">
                    <img :src="`http://localhost:7758/images/${scope.row.photo}`" width="150px" height="100px">
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" type="danger" @click="del(scope.row)">删除</el-button>
                    <el-button size="mini" type="info" @click="updateUI(scope.row)">修改</el-button>
                    <el-button size="mini" @click="distributeRoleUI(scope.row)">分配角色</el-button>
                </template>

            </el-table-column>
        </el-table>

        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
            :page-sizes="[5, 10, 15, 20]" :page-size="100" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
    </div>
</template>
  
<script>
import axios from '@/util/request.js';
import { getUser, getRoles,doDistributeRole} from '@/api/user/user.js';
export default {
    data() {
        return {
            dialogRoleFormVisible: false,
            name: "",
            dialogFormVisible: false,
            form: {
            },
            formInline: {
                deptName: "",
                name: ""
            },
            total: 0,
            formLabelWidth: '120px',
            tableData: [],
            pageNum: 1,
            pageSize: 5,
            user:{},
            roles: [],
            value: [],
            filterMethod(query, item) {
                return item.pinyin.indexOf(query) > -1;
            }
        }
    },
    methods: {
        distributeRoleUI(row) {
            this.dialogRoleFormVisible = true;
            getUser(row.userId).then(r => {
                this.user=r.data
                this.value = r.data.roles.map(role => {
                    return role.roleId
                })
                console.log(this.value);
            })
            getRoles().then(r => {
                this.roles = r.data
                this.data = this.roles
            })
            
        },
       doDistributeRole(userId){
         let roles = this.value
        doDistributeRole(userId,roles).then(r=>{
                if(r.code==200){
                    this.$message.success("分配成功")
                }else{
                    this.$message.warning("分配失败")
                }
            })
       },
        handleSizeChange(size) {
            this.pageSize = size;
            this.getList();
        },
        handleCurrentChange(page) {
            this.pageNum = page;
            this.getList();
        },
        saveUI() {
            this.form = {}
            this.dialogFormVisible = true;
            if (this.$refs.file) {
                this.$refs.file.value = ''
            }
        },
        submitform() {
            if (!this.form.userId) {
                let file = this.$refs.file.files[0];
                let formData = new FormData();
                formData.append("username", this.form.username);
                formData.append("password", this.form.password);
                formData.append("userAge", this.form.userAge);
                formData.append("userPhone", this.form.userPhone);
                formData.append("photoData", file);
                console.log(formData);
                axios.post("user/save", formData).then(r => {
                    if (r.code == 200) {
                        this.dialogFormVisible = false
                        this.getList();
                        this.$message.success(r.msg)
                        return;
                    }
                    this.$message.error(r.msg)
                })
                return;
            }
            let file = this.$refs.file.files[0];
            let formData = new FormData();
            formData.append("userId", this.form.userId);
            formData.append("username", this.form.username);
            formData.append("password", this.form.password);
            formData.append("userAge", this.form.userAge);
            formData.append("userPhone", this.form.userPhone);
            formData.append("photoData", file);
            console.log(formData);
            axios.post("user/update", formData).then(r => {
                if (r.code == 200) {
                    this.dialogFormVisible = false
                    this.getList();
                    this.$message.success(r.msg)
                    return;
                }
                this.$message.error(r.msg)
            })

        },
        getList() {
            axios.post(`/user/findSomeByPage/${this.pageNum}/${this.pageSize}`)
                .then(r => {
                    if (r.code === 200) {
                        this.tableData = r.data.list;
                        this.total = r.data.total
                    }
                })
        },
        del(row) {
            this.$confirm("确认删除？").then(() => {
                let id = row.userId;
                let filename = row.photo;
                axios.post(`user/delete/${id}/${filename}`).then(r => {
                    if (r.code = 200) {
                        this.$message.success("删除成功")

                    } else {
                        this.$message.error("删除失败")
                    }
                    this.getList()
                })
            })
        },
        updateUI(row) {
            let str = JSON.stringify(row)
            let json = JSON.parse(str)
            this.form = json
            this.dialogFormVisible = true
            if (this.$refs.file) {
                this.$refs.file.value = ''
            }
        }

    },
    mounted() {
        this.getList()
    }
}
</script>